﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 二维码生成工具
{
    /// <summary>
    /// Hnzy.xaml 的交互逻辑
    /// </summary>
    public partial class Hnzy : Page
    {
        private static char[] constant =
        {
        '0','1','2','3','4','5','6','7','8','9',
        'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
        };
        private static int Progress = 0;
        private delegate void UpdateProgressBarDelegate(System.Windows.DependencyProperty dp, Object value);

        public Hnzy()
        {
            InitializeComponent();
        }

         

     

        private void batch_No_TextChanged(object sender, TextChangedEventArgs e)
        {
            Regex rgx = new Regex(@"^\d+$");

            string ss = (sender as TextBox).Text;

            if (!rgx.IsMatch(ss))
            {
                (sender as TextBox).Text = "";
            }
            else
            {
                if ((sender as TextBox).Name == "num")
                {
                    int Num = Convert.ToInt32((sender as TextBox).Text);
                    if (Num < 1)
                    {
                        (sender as TextBox).Text = "";
                    }
                    else if(Num>500000)
                    {

                        MessageBox.Show("一次最多生成50W");
                        (sender as TextBox).Text = "500000";

                    }

                }
            }

         
             

        }
  

        private void Button_Click(object sender, RoutedEventArgs e)
        {

         
            string Domain = domain.Text;
            string Batch_No = batch_No.Text;

            int start = 1;
            
            if (Domain==null) {
                start = 0;
                MessageBox.Show("域名不能为空" );
            }

            if (Batch_No == null)
            {
                start = 0;
                MessageBox.Show("批次号不能为空" );
            }

            if(Batch_No.Length!=5)
            {
                start = 0;
                MessageBox.Show("随机码长度需要5位");
            }

            if (num.Text == null)
            {
                start = 0;
                MessageBox.Show("数量不能为空");
            }
        
            if(start ==1){
               


                Microsoft.Win32.SaveFileDialog ofd = new Microsoft.Win32.SaveFileDialog();
              

                ofd.Filter = "txt files(*.txt)|*.txt|xls files(*.xls)|*.xls|All files(*.*)|*.*";

                //设置默认文件名（可以不设置）
                ofd.FileName = "RootElements";
                //主设置默认文件extension（可以不设置）
                ofd.DefaultExt = "txt";

                //获取或设置一个值，该值指示如果用户省略扩展名，文件对话框是否自动在文件名中添加扩展名。（可以不设置）
                ofd.AddExtension = true;

                if (ofd.ShowDialog() == true)
                {
                   

                    int Num = Convert.ToInt32(num.Text);

                    FileStream fs1 = new FileStream(ofd.FileName, FileMode.Create, FileAccess.Write);//创建写入文件 
                    StreamWriter sw = new StreamWriter(fs1);

                    pb_import.Maximum = Num;
                    pb_import.Value = 0;

                    UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(pb_import.SetValue);
                     int  k = Num / 10 ;
                    for (int i = 0; i < Num; i++)
                    {

                        string timeStamp = Random6(Convert.ToInt32(GetTimeStamp()), i);

                        
                        string code;
                        Random radnom = new Random();
                        int x, y, z;
                        x= radnom.Next(0, 15);
                        y= radnom.Next(0, 15-x);
                        z = 15 - x - y;
                        if (has_verify.IsChecked == true)
                        {
                            //4位62进制随机数+4位62进制时间戳+8随机数+2位随机数
                              code = Domain.Trim() + Batch_No +"/"+ GetRandomString(x, true, true, true, false, "") + timeStamp + GetRandomString(y, true, true, true, false, Convert62(238328 + i, 62)) + GetRandomString(z, true, true, true, false, "")+","+ GetRandomString(4, true, false, false, false, "");

                        }
                        else {
                            //4位62进制随机数+5位62进制时间戳+8随机数+2位随机数
                            code = Domain.Trim() +  Batch_No + "/" + GetRandomString(x, true, true, true, false, "") + timeStamp + GetRandomString(y, true, true, true, false, Convert62(238328 + i, 62)) + GetRandomString(z, true, true, true, false, "");
                        }
                     

                        
                    
                        if (Progress < Num && Progress == i) {
                           
                            Dispatcher.Invoke(
                              updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[]
                                       {
                                           System.Windows.Controls.ProgressBar.ValueProperty,
                                            Convert.ToDouble(i + 1)
                                       }
                                     );
                            Progress = Progress + k;
                       
                            if (Progress >= Num) {
                                Progress = Num-1;
                            }
                        }

                        sw.WriteLine( code);//开始写入值

                        
                    }

                    this.tb.Text = "本次共生成随机码:" + Convert.ToString(Num)+ "条";
                    MessageBox.Show("本次共生成" + Num + "条随机码");
                    sw.Close();
                    fs1.Close();

                }

            }
             

          


        }
 
         
        

        // 根据时间戳生成一个6位的随机码
        private string Random6(int timeStamp, int i){

            timeStamp =   timeStamp- 1000000000+i;

            //62进制的时间戳
            return  Convert62(timeStamp, 62);
        }

        ///<summary>
        ///生成随机字符串 
        ///</summary>
        ///<param name="length">目标字符串的长度</param>
        ///<param name="useNum">是否包含数字，1=包含，默认为包含</param>
        ///<param name="useLow">是否包含小写字母，1=包含，默认为包含</param>
        ///<param name="useUpp">是否包含大写字母，1=包含，默认为包含</param>
        ///<param name="useSpe">是否包含特殊字符，1=包含，默认为不包含</param>
        ///<param name="custom">要包含的自定义字符，直接输入要包含的字符列表</param>
        ///<returns>指定长度的随机字符串</returns>
        public static string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
        {
            byte[] b = new byte[4];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
            Random r = new Random(BitConverter.ToInt32(b, 0));
            string s = null, str = custom;
            if (useNum == true) { str += "0123456789"; }
            if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
            if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
            if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
            for (int i = 0; i < length; i++)
            {
                s += str.Substring(r.Next(0, str.Length - 1), 1);
            }
            return s;
        }

        //62进制

        private string Convert62(int n, int Base)
        {
            bool gt0 = true;
            if (Base < 10 || Base > 62) return null;
            if (n == 0) return "0";
            if (n < 0)
            {
                n = -n;
                gt0 = false;
            }
            StringBuilder sb = new StringBuilder();
            string t = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            while (n > 0)
            {
                sb.Append(t[n % Base]);
                n /= Base;
            }
            t = sb.ToString();
            n = t.Length;
            sb.Length = 0;
            if (!gt0) sb.Append("-");
            while (--n >= 0) sb.Append(t[n]);
            return sb.ToString();
        }

        /// 获取时间戳  
        /// </summary>  
        /// <returns></returns>  
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        
       

        private void beginImport(int num)
        {
            pb_import.Maximum = num;
            pb_import.Value = 0;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(pb_import.SetValue);

            for (int i = 0; i < 100; i++)
            {
                Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(i + 1) });
            }
        }


    }
}
